package com.shuyan.base.algorithm;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Exercise03 {
    public static void main(String[] args) {
        String yearMonth="2021-03";
        int year=Integer.parseInt(yearMonth.split("-")[0]);
        int month=Integer.parseInt(yearMonth.split("-")[1]);
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.YEAR,year);
        cal.set(Calendar.MONTH,month-1);
        int lastMonthDay=cal.getActualMaximum(Calendar.DATE);
        cal.set(Calendar.DATE,lastMonthDay);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth=sdf.format(cal.getTime());
        String lastSecondOfMonth=lastDayOfMonth+" 23:59:59";
        try {
            Date lastSecondOfMonthDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(lastSecondOfMonth);
            Date lastSecondOfMonthDate2= getLastDayOfMonth(2021,3);
            System.out.println(lastSecondOfMonthDate);
            System.out.println(lastSecondOfMonthDate2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String day=getLastDayOfMonth2(2021,2);
        System.out.println(day);

    }
    public static Date getLastDayOfMonth(Integer year, Integer month) {
        Calendar calendar = Calendar.getInstance();
        if (year == null) {
            year = calendar.get(Calendar.YEAR);
        }
        if (month == null) {
            month = calendar.get(Calendar.MONTH);
        }
        calendar.set(year, month, 1);
        calendar.roll(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String day_last = df.format(calendar.getTime());
        StringBuffer endStr = new StringBuffer().append(day_last).append(" 23:59:59");
        day_last = endStr.toString();
        Date lastDate = null;
        try {
            lastDate = sdf.parse(day_last);

        } catch (java.text.ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return lastDate;
    }
    public static String getLastDayOfMonth2(Integer year, Integer month) {
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.YEAR,year);
        cal.set(Calendar.MONTH,month-1);
        int lastMonthDay=cal.getActualMaximum(Calendar.DATE);
        cal.set(Calendar.DATE,lastMonthDay);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth=sdf.format(cal.getTime());
        return lastDayOfMonth;
    }
    }

